package com.baoxin.chenxixc4coach;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

public class SplashActivity extends BaseActivity {

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        };

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isLogined()) {
                            Intent it = new Intent(SplashActivity.this, LoginActivity.class);
                            startActivity(it);
                            finish();
                        }

                    }
                });
            }
        };
        timer.schedule(task, 1000);

    }

    @Override
    protected void onStart() {
        uiOpions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        super.onStart();
    }

    private boolean isLogined() {
        String userName = MyApplication.getUserName();
        String password = MyApplication.getPassword();
        if (userName.length() == 11) {
            login(userName, password);
            return true;
        } else {
            return false;
        }
    }

    private void login(String userName, String password) {
        JSONObject body = new JSONObject();
        try {
            body.put("phone", userName);
            body.put("password", password);
            body.put("type", 0);
            NetUtil.post(this, Interfaces.URL_LOGIN_IN, body.toString(),
                    new MyCallback(Interfaces.URL_LOGIN_IN, handler));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

